<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/9
 * Time: 16:07
 */
namespace app\api\controller;
use think\Controller;
use think\Db;
import('wxpay.WxPay_Api', EXTEND_PATH);
import('wxpay.WxPay_Notify', EXTEND_PATH);
import('wxpay.WxPay_Sign', EXTEND_PATH);
import('wxpay.log', EXTEND_PATH);



class Wxrtn{
    public function wxnotify(){
//初始化日志
        if (!is_dir('./logs/')) {
            mkdir('./logs/', 0755, true);
        }
        echo 'weChatPayRtn';
        $logHandler= new \CLogFileHandler("./logs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);
        $notify = new PayNotifyCallBack();
        $log->DEBUG('begin notify');
        $notify->Handle(true);
    }
}

class PayNotifyCallBack extends \WxPayNotify
{
    //查询订单
    public function Queryorder($transaction_id)
    {
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = \WxPayApi::orderQuery($input);
        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS")
        {
            return true;
        }
        return false;
    }

    //重写回调处理函数
    public function NotifyProcess($data, &$msg)
    {

        $logHandler= new \CLogFileHandler("./logs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);

        if(!array_key_exists("transaction_id", $data)){
            $msg = "输入参数不正确";
            $log->DEBUG($msg);
            return false;
        }
        //查询订单，判断订单真实性
        if(!$this->Queryorder($data["transaction_id"])){
            $msg = "订单查询失败";
            $log->DEBUG($msg);
            return false;
        }
        $money = $data['total_fee'];//获得金额
        $where['recharge_no'] = $data['out_trade_no'];//订单编号

        //用户订单查询
        $info = Db::name('recharge_record')->where($where)->find();

        if($info){
            $log->DEBUG('recharge_id:'.$info['recharge_id']);
            $log->DEBUG('recharge_no:'.$info['recharge_no']);

            if((int)$info['is_success'] == 2 && is_numeric($money)) {

                Db::name('recharge_record')->where($where)->setField('is_success',1);

                return true;//支付成功
            }

        }

        //支付失败
        $log->DEBUG('success:');
        $log->DEBUG('out_trade_no:'.$data['out_trade_no']);
        $success = false;
        return $success;//是否支付成功
    }
}